package com.wechat.core;

import java.beans.IntrospectionException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wechat.model.response.TextMessage;
import com.wechat.utils.WechatMessageUtils;

/**
 * 处理微信推送过来的消息
 */
@Controller
@RequestMapping(value="/wechatMsg")
public class WechatMsgController {
	@RequestMapping(value = "/getMsg")
	@ResponseBody
	public String getMsg(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		response.setCharacterEncoding("utf-8");
		String method = request.getMethod();
		System.out.println("=========进入======getMsg方法=======method===="+method+"=======");
		if (WechatMessageUtils.METHODGET.equals(method)) {
		    System.out.println("=========进入======get==================");
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			System.out.println("d"+signature+",    "+timestamp+",     "+nonce+",   "+echostr);
			response.reset();
			PrintWriter out = response.getWriter();
			System.out.println("b"+signature+",    "+timestamp+",     "+nonce+",   "+echostr);
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (WechatMessageUtils.checkSignature(signature, timestamp, nonce)) {
				System.out.println("a"+signature+",    "+timestamp+",     "+nonce);
				out.print(echostr);
			}
			out.close();
			out = null;
		}
		if (WechatMessageUtils.METHODPOST.equals(method)) {
		    System.out.println("========进入=======post==================");
			// 调用核心业务类接收消息、处理消息
			String respMessage = processRequest(request);
			// 响应消息
			PrintWriter out = response.getWriter();
			out.print(respMessage);
			out.close();
		}
		return "";
	}
	/**
	 * 处理微信发来的请求
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public String processRequest(HttpServletRequest request) throws Exception {
		String respMessage = null;
		// xml请求解析
		Map<String, String> requestMap = WechatMessageUtils.parseXml(request);
		// 发送方帐号（open_id）
		String fromUserName = requestMap.get("FromUserName");
		// 公众帐号
		String toUserName = requestMap.get("ToUserName");
		// 消息类型
		String msgType = requestMap.get("MsgType");
		// 文本消息
		if (msgType.equals(WechatMessageUtils.REQ_MESSAGE_TYPE_TEXT)) {
			return noReply(fromUserName, toUserName);
		}
		// 图片消息
		else if (msgType.equals(WechatMessageUtils.REQ_MESSAGE_TYPE_IMAGE)) {
		}
		// 事件推送
		else if (msgType.equals(WechatMessageUtils.REQ_MESSAGE_TYPE_EVENT)) {
			// 事件类型
			String eventType = requestMap.get("Event");
			if(eventType.equals(WechatMessageUtils.EVENT_TYPE_CLICK)){
				String eventKey = requestMap.get("EventKey");
				System.out.println(eventKey);
				//联系我们
				if (eventKey.equals("15")) {
					respMessage = connectOurs(fromUserName, toUserName);
				}
				//关于我们
				if (eventKey.equals("16")) {
					respMessage = aboutOurs(fromUserName, toUserName);
				}
			}
			//首次关注推送欢迎语
			if(eventType.equals(WechatMessageUtils.EVENT_TYPE_SUBSCRIBE)){
				respMessage = subscribeString(fromUserName, toUserName);
				System.out.println(respMessage);
				String e = requestMap.get("EventKey");
				System.out.println("此数据为推荐用户关注人的e:"+e+"  |||||------------------------");
				System.out.println("goin-----for------save------and-this--is-----"+fromUserName);
//				User u=memberService.findOne(User.class, "openId", fromUserName, null);
				System.out.println("-------saveing------------------------");
			}
			if(eventType.equals(WechatMessageUtils.EVENT_TYPE_UNSUBSCRIBE)){
				System.out.println("goin-----for------save------and-this--is-----"+fromUserName);
//				User u=memberService.findOne(User.class, "openId", fromUserName, null);
				System.out.println("-------saveing------------------------");
			}
		}
		return respMessage;
	}
	private String noReply(String fromUserName,String toUserName){
		//		TextMessage textMessage = new TextMessage();
		//		textMessage.setToUserName(fromUserName);
		//		textMessage.setFromUserName(toUserName);
		//		textMessage.setCreateTime(new Date().getTime());
		//		textMessage.setMsgType(WechatMessageUtils.RESP_MESSAGE_TYPE_TEXT);
		//		textMessage.setFuncFlag(0);
		//		textMessage.setContent("");
		//		return WechatMuessageUtils.textMessageToXml(textMessage);
		// 现在什么都不回复
		return "";
	}
	/*
	 * 联系我们
	 */
	public String connectOurs(String fromUserName,String toUserName){
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(WechatMessageUtils.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		textMessage.setContent("北京\n"
				+ "QQ:3217100096\n"
				+ "电话:0471-5974886");
		System.out.println(WechatMessageUtils.textMessageToXml(textMessage));
		return WechatMessageUtils.textMessageToXml(textMessage);
	}
	public static void main(String[] args) {
		new WechatMsgController().connectOurs("z", "a");
	}
	/*
	 * 关于我们 
	 */
	public String aboutOurs(String fromUserName,String toUserName){
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(WechatMessageUtils.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		textMessage.setContent("我们是一家基于O2O运营模式的新型互联网企业，采用线上线下紧密结合相互作用，使我们在互联网上进行相对应的操作之后，使每一位用户享受到线下优质的服务。");
		return WechatMessageUtils.textMessageToXml(textMessage);
	}
	
	/**
	 * 首次关注欢迎语
	 * @param fromUserName
	 * @param toUserName
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws IntrospectionException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/test")
	private String subscribeString(String fromUserName,String toUserName) throws IllegalAccessException, InvocationTargetException, IntrospectionException, UnsupportedEncodingException{
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(WechatMessageUtils.RESP_MESSAGE_TYPE_TEXT);
		
		textMessage.setContent("欢迎您加入大陆汽车救援！");
		return WechatMessageUtils.textMessageToXml(textMessage);
	}
}
